package com.myrent.shiro;

import com.myrent.entity.User;
import com.myrent.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

public class UserRealm extends AuthorizingRealm {
    @Autowired
    UserService userService;

    { super.setName("User"); }

    /**
     * 授权
     * 即登录过后，每个身份不一定，对应的所能看的页面也不一样。
     * @param principals
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //获取当期用户
        Object principal = principals.getPrimaryPrincipal();
        Set<String> roles = new HashSet<>();
        roles.add("user");
        if ("admin".equals(principal)) {
            ///如果从数据库中查到了principal是admin的话，就给他赋予admin的权限
            roles.add("admin");
        }
        //绑定角色与资源
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles);
        return info;
    }

    /**
     * 身份认证
     * 即登录通过账号和密码验证登陆人的身份信息
     * @param token
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
//        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        CustomizedToken usernamePasswordToken = (CustomizedToken) token;
        String username = usernamePasswordToken.getUsername();
        User user = userService.getUserByPhoneNum(username);
        if (user == null) {
            //登入失败
            return null;
        }
        ByteSource salt = ByteSource.Util.bytes(user.getSalt());
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user.getPhoneNum(), user.getPassword(), salt,
                getName());
        return info;
    }
}
